package com.gebiafu.security;

import com.gebiafu.exception.DaoException;
import com.gebiafu.pojo.User;
import com.gebiafu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * title: UserLoginService
 * author: Gebiafu
 * date: 2021/07/02 11:22
 */
@Component
public class UserLoginService implements UserDetailsService {
    @Autowired
    private UserService userService;
    //登陆逻辑
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据登陆名查询用户
        User user=null;
        try {
            user = userService.findUser(username);
        } catch (DaoException e) {
            e.printStackTrace();
            //查询用户错误,通知登陆失败
            throw new UsernameNotFoundException("用户登陆失败,用户不存在");
        }
        //处理权限
        String[] authorities = user.getAuthorities().split(";");
        //创建返回结果对象
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                AuthorityUtils.createAuthorityList(authorities)
        );


    }
}
